package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.HexStrTransformUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Getter
@NoArgsConstructor
public class InnerClasses extends AttributeInfo {
	private Integer numberOfClasses;
	private List<Classes> classesList;

	public InnerClasses(Integer numberOfClasses, List<Classes> classesList) {
		this.numberOfClasses = numberOfClasses;
		this.classesList = classesList;
	}

	class Classes {
		private Integer innerClassInfoIndex;
		private Integer outerClassInfoIndex;
		private Integer innerNameIndex;
		private Integer innerClassAccessFlags;

		public Classes() {
		}

		public Classes(Integer innerClassInfoIndex, Integer outerClassInfoIndex, Integer innerNameIndex, Integer innerClassAccessFlags) {
			this.innerClassInfoIndex = innerClassInfoIndex;
			this.outerClassInfoIndex = outerClassInfoIndex;
			this.innerNameIndex = innerNameIndex;
			this.innerClassAccessFlags = innerClassAccessFlags;
		}
	}

	public InnerClasses(Integer attributeNameIndex, Integer attributeLength, Integer numberOfClasses, List<Classes> classesList) {
		super(attributeNameIndex, attributeLength);
		this.numberOfClasses = numberOfClasses;
		this.classesList = classesList;
	}

	@Override
	protected InnerClasses newAttributeInfo(Integer attributeNameIndex, Integer attributeLength, ClassFile classFile) {
		this.numberOfClasses = HexStrTransformUtil.parseHexToInt(classFile.readU2());
		List<Classes> classesList = new ArrayList<>(numberOfClasses);
		for (int i = 0; i < numberOfClasses; i++) {
			Integer innerClassInfoIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer outerClassInfoIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer innerNameIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer innerClassAccessFlags = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			classesList.add(new Classes(innerClassInfoIndex, outerClassInfoIndex, innerNameIndex, innerClassAccessFlags));
		}
		this.classesList = classesList;
		return this;
	}
}
